#include "font.h"
#include <sdl/sdl.h>
#include <malloc.h>

using namespace std;

Font::Font(char *name){
    load(name);
}

void Font::load(char *name){
    mSurface = SDL_LoadBMP(name);
    mCharW = mSurface->w/16;
    mCharH = mSurface->h/16; 
}

void Font::drawChar(int x,int y,unsigned char c){
    SDL_Rect drc = {x,y,mCharW,mCharH};
    int off_x = (c%16)*mCharW;
    int off_y = (c/16)*mCharH;
    SDL_Rect src = {off_x,off_y,mCharW,mCharH};
    
    SDL_BlitSurface(mSurface,&src,SDL_GetVideoSurface(),&drc);
    //printf("off_x: %d,off_y: %d; char_w: %d\n",off_x,off_y,font->char_w);
}

void Font::drawText(int x,int y,char *text){
    int i;
    int off_x = 0, off_y = 0;
    for(i = 0; text[i] != 0; i++){
        if(text[i] == 0x0A){
            off_x = 0;
        }
        else if(text[i] == 0x0D){
            off_y += mCharH;
        }
        else {
            drawChar(x+off_x,y+off_y,text[i]);
            off_x += mCharW;
        }
    }
}

void Font::setTransparent(int color){
    SDL_SetColorKey(mSurface,SDL_SRCCOLORKEY,color);
}

Font *g_StdFont;

void SetStdFont(Font *font){
    g_StdFont = font;
}

void DrawText(int x,int y,char *text){
    if(g_StdFont != 0){
        g_StdFont->drawText(x,y,text);
    }
}

void DrawChar(int x,int y,unsigned char c){
    if(g_StdFont != 0){
        g_StdFont->drawChar(x,y,c);
    }
}


